package Collection.hash.HashMap.HashCode.Util;

import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * Map工具类
 *
 * @author: 张从龙
 * time: 2023/2/13 11:01
 */
public class MapUtil {
    private MapUtil() {
    }
    public static void main(String args[]) {
        Instant start = Instant.now();

        Map<String, String> map = new TreeMap<>();
        map.put("1$1$1$1", "obj1");
        map.put("1$1$1$2", "obj2");

        map.put("1$1$2$1", "obj3");
        map.put("1$1$2$2", "obj4");
        map.put("1$2$1$1", "obj5");
        map.put("2$2$1$1", "obj6");

        List<String> list = get(map, "1$1$1");
        for (String s : list) {
            System.out.println(s);
        }

        Duration dur = Duration.between(start, Instant.now());
        System.out.println("【耗时】（ms）" + dur.toMillis());
    }

    /**
     * 根据key模糊搜索Map
     *
     * @author: 张从龙
     * time: 2023/2/14 11:06
     */
    public static <T> List<T> get(Map<String, T> map, String key) {
        String[] strArray = map.keySet().toArray(new String[0]);
        List<T> list = new ArrayList<>();

        boolean isFound = false;
        for (String str : strArray) {
            if (str.startsWith(key)) {
                list.add(map.get(str));
                isFound = true;
            } else if (isFound) {
                break;
            }
        }
        return list;
    }

    /**
     * 根据map的key进行字典升序排序
     */
    public static Map<String, String> sortMapByKey(Map<String, String> map) {
        Map<String, String> treemap = new TreeMap<>(map);
        List<Map.Entry<String, String>> list = new ArrayList<>(treemap.entrySet());
        list.sort(Map.Entry.comparingByKey());
        return treemap;
    }
}